package panda.query.util;

import java.util.List;

import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.struct.Constant;
import panda.query.struct.NullConstant;

public class GroupByComparator implements Comparator {
	
	List<Attribute> attrs;
	
	/**
	 * 
	 * @param attrs On which attributes to compare
	 */
	public GroupByComparator(List<Attribute> attrs) {
		this.attrs = attrs;
	}
	
	/**
	 * Compare the tuple refered to by the two scanners
	 * @param a
	 * @param b
	 * @return
	 */
	public int compare(Scanner a, Scanner b) {
		int res = 0, temp;
		boolean nullA = false, nullB = false; 
		
		for (int i = 0; i < attrs.size(); i++) {
			Constant ca = a.getValue(attrs.get(i));
			Constant cb = b.getValue(attrs.get(i));
			
			if (ca instanceof NullConstant) nullA = true;
			if (cb instanceof NullConstant) nullB = true;
			if (!(ca instanceof NullConstant && cb instanceof NullConstant)
			&& (res == 0 && (temp = ca.compareTo(cb)) != 0))
				res = temp;
		}
		
		if (nullA != nullB) {
			if (nullA) return 1; else return -1;
		}
		else
			return res;
		
	}
}
